package data

import (
	"commerce/common"
	"commerce/model"
	"fmt"
	"strconv"
	"time"
)

func PageCollect(pageNo, pageSize int, mid int) (*common.Page, error) {

	row := common.DB.QueryRow("select count(*) FROM goods_collect where member_id = " + strconv.Itoa(mid))
	var totalRecords int
	if err := row.Scan(&totalRecords); err != nil {
		return nil, err
	}
	stmt, err := common.DB.Prepare("select id, sku_id FROM goods_collect LIMIT ?, ?")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query((pageNo-1)*pageSize, pageSize)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var cs []model.GoodsCollect
	for rows.Next() {
		c := model.GoodsCollect{}
		if err := rows.Scan(&c.Id, &c.SkuId); err != nil {
			return nil, fmt.Errorf("收藏商品分页数据有误:%s", err.Error())
		}
		cs = append(cs, c)
	}
	return common.NewPage(cs, pageNo, pageSize, totalRecords), nil
}

func AddGoodsCollect(c model.GoodsCollect) (int, error) {

	sqlTpl := `replace into goods_collect(sku_id, member_id, created_time) VALUES (?, ?, ?)`

	stmt, err := common.DB.Prepare(sqlTpl)
	if err != nil {
		return 0, err
	}
	defer stmt.Close()
	result, err := stmt.Exec(c.SkuId, c.MemberId, time.Now().Add(8*time.Hour))

	if err != nil {
		return 0, fmt.Errorf("save goods collect err: %v", err)
	}
	id, err := result.LastInsertId()

	if err != nil {
		return 0, fmt.Errorf("save goods collect insert id err: %v", err)
	}
	return int(id), nil
}

func DeleteGoodsCollectById(collectId int) error {

	stmt, err := common.DB.Prepare("delete from goods_collect where id = ?")
	if err != nil {
		return err
	}
	defer stmt.Close()

	_, err = stmt.Exec(collectId)

	return err
}

func DeleteGoodsCollect(memberId, skuId int) error {

	stmt, err := common.DB.Prepare("delete from goods_collect where member_id = ? and sku_id = ?")
	if err != nil {
		return err
	}
	defer stmt.Close()

	_, err = stmt.Exec(memberId, skuId)

	return err
}

func CountGoodsCollect(memberId, skuId int) (int, error) {

	stmt, err := common.DB.Prepare("select count(*) from goods_collect where member_id = ? and sku_id = ?")
	if err != nil {
		return 0, err
	}
	defer stmt.Close()

	row := stmt.QueryRow(memberId, skuId)

	var totalRecords int
	if err := row.Scan(&totalRecords); err != nil {
		//if err == sql.ErrNoRows {
		//	return 0, nil
		//}
		return 0, err
	}
	return totalRecords, nil
}

func ListSkuIdByMemberId(memberId int) ([]int, error) {

	stmt, err := common.DB.Prepare("select sku_id FROM goods_collect where member_id = ?")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query(memberId)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var ks []int
	for rows.Next() {
		var skuId int
		if err := rows.Scan(&skuId); err != nil {
			return nil, fmt.Errorf("查询会员收藏商品数据有误:%s", err.Error())
		}
		ks = append(ks, skuId)
	}
	return ks, nil
}
